const db = wx.cloud.database()
const data = db.collection('waterQuilt')
var util = require('../../../../util/data.js')
var TIME = util.formatTime(new Date())

Page({
  data: {
    url: "https://m.qpic.cn/psc?/V51688fg1vRc9q3n3omH2cRMjT0zxtCE/45NBuzDIW489QBoVep5mcYagQ26vAbbb4pk*mxKiZZmlrWXixxJKij7h23gfAAqji84p2oZ5NuBhjWhrBJi05durafpjcNuqmDBM*Yv1guY!/b&bo=XgT.BV4E*gUBGT4!&rf=viewer_4&t=5",
    date: TIME,
    show: false,
    userInfo: "",
    fileList: [],
    accountIndex: 0,
    accounts: ["榆中校区", "新村校区"],
    imgbox: [], //选择图片
    fileIDs: [], //上传云存储后的返回值
    placeholder:"请输入物品详细描述"
  },
  onLoad(){
    var that = this 
    wx.getUserInfo({
      success: res => {
        that.setData({
          infoImage:res.userInfo.avatarUrl,
          infoName:res.userInfo.nickName
        })
      }
    })
  },
  //保存图片
  ImagePreview(e) {
    console.log(e)
    var that = this;
    var src = e.target.dataset.url; //获取data-src
    var imgList = [e.target.dataset.url]; //获取data-list
    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
  getUserInfo(event) {
    this.setData({
      show: false
    });
  },

  onClose() {
    wx.navigateBack({
      delta: 2,
    })
    this.setData({
      close: false
    });
  },

  bindAccountChange: function (e) {
    this.setData({
      accountIndex: e.detail.value
    })
  },

  // 删除照片 &&
  imgDelete1: function (e) {
    let that = this;
    let index = e.currentTarget.dataset.deindex;
    let imgbox = this.data.imgbox;
    imgbox.splice(index, 1)
    that.setData({
      imgbox: imgbox
    });
  },

  // 选择图片 &&&
  addPic1: function (e) {
    var imgbox = this.data.imgbox;
    console.log(imgbox)
    var that = this;
    var n = 5;
    if (5 > imgbox.length > 0) {
      n = 5 - imgbox.length;
    } else if (imgbox.length == 5) {
      n = 1;
    }
    wx.chooseImage({
      count: n, // 默认9，设置图片张数
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // console.log(res.tempFilePaths)
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths

        if (imgbox.length == 0) {
          imgbox = tempFilePaths
        } else if (5 > imgbox.length) {
          imgbox = imgbox.concat(tempFilePaths);
        }
        that.setData({
          imgbox: imgbox
        });
      }
    })
  },

  //图片
  imgbox: function (e) {
    this.setData({
      imgbox: e.detail.value
    })
  },


  //发布按钮
  formSubmit: function (e) {
    const that = this
    if (e.detail.value.title == '' || e.detail.value.price == '' || e.detail.value.wechart == '' || !this.data.imgbox.length) {
      wx.showModal({
        title: '提示',
        content: '请将信息补充完整',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    } else {
      wx.showLoading({
        title: '提交中...',
      })
      let promiseArr = [];
      for (let i = 0; i < this.data.imgbox.length; i++) {
        promiseArr.push(new Promise((reslove, reject) => {
          let item = this.data.imgbox[i];
          let suffix = /\.\w+$/.exec(item)[0]; //正则表达式返回文件的扩展名
          wx.cloud.uploadFile({
            cloudPath: 'waterQuilt/' + new Date().getTime() + suffix, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {

              this.setData({
                fileIDs: this.data.fileIDs.concat(res.fileID)
              });
              console.log(res.fileID) //输出上传后图片的返回地址
              reslove();
              wx.hideLoading();

            },
            fail: res => {
              wx.hideLoading();

            }

          })
        }));
      }
      Promise.all(promiseArr).then(res => { //等数组都做完后做then方法
        console.log("图片上传完成后再执行")
        this.setData({
          imgbox: []
        })

        that.fb(e)
      })

    }
  },
  //  添加数据到数据库
  fb: function (event) {
    var that = this

    data.add({
      data: {
        title: event.detail.value.title,
        price: event.detail.value.price,
        wechart: event.detail.value.wechart,
        qq: event.detail.value.qq,
        time: that.data.date,
        mode: that.data.accounts[event.detail.value.mode],
        fileList: that.data.fileIDs,
        waterQuilt:"水票",
        information: event.detail.value.information,
        over: 'no',
        show: 'no',
        infoImage:that.data.infoImage,
        infoName:that.data.infoName
      },
      success: function (res) {
        wx.hideLoading({
          success: (res) => {},
        })
        that.setData({
          placeholder:"",
          show: true,
          fileIDs: []
        })
      },

    })
  },

  clearInputEvent: function (e) {
    this.setData({
      title: '',
      content: '',
      price: ''
    })
  }
})